package basic.sort.string;

/**
 * @author distantstar
 * @version 1.0
 * @date 2021
 * @description basic.sort.string
 * @since JDK1.8
 */
public class TransNum {
    public static int strToInt(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }

        // 字符数组
        char[] chars = str.toCharArray();
        // 判断当前字符是否是第一个非空字符
        boolean isFirst = true;
        // 拼接的字符串
        StringBuilder builder = new StringBuilder();
        // 正数与否
        boolean isPositive = false;
        // 循环拼接
        for (char ch: chars) {
            if (ch == ' ' && isFirst) {
                continue;
            }
            // 假如不为空并且是第一个非空字符
            if (ch != ' ' && isFirst) {
                // 判断是否是数字字符
                if (!isDigit(ch)) {
                    // 不是则判断是不是正负号
                    if (ch == '+') {
                        isPositive = true;
                    } else if (ch == '-') {
                        
                    } else {
                        return 0;
                    }
                    isFirst = false;
                } else {
                    // 是数学字符，则可以直接添加
                    isFirst = false;
                    isPositive = true;
                    builder.append(ch);
                }
            } else {
                if (!isDigit(ch)) {
                    break;
                } else {
                    builder.append(ch);
                }
            }
        }

        long num = transNum(builder);
        if (isPositive && num > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
        } else if(!isPositive && num > 2147483648L) {
                return Integer.MIN_VALUE;
        } else {
            if (isPositive) {
                return (int)num;
            } else {
                return -(int)num;
            }
        }
    }

    private static boolean isDigit(char ch) {
        return ch >= '0' && ch <= '9';
    }

    private static long transNum(StringBuilder builder) {
        while (builder.charAt(0) == '0') {
            builder.deleteCharAt(0);
        }

        return Long.parseLong(builder.toString());
    }

    public static void main(String[] args) {
        System.out.println(strToInt("-91283472332"));
    }
}
